package com.example.contentclient;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.example.contentclient.Util.PermissionUtil;

import java.io.File;

public class InstallApkActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String[]PERMISSIONS=new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private static final int PERMISSION_REUQEST_CODE=1;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_installapk);
        findViewById(R.id.btn_install).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.R) {
            Log.d("tang", "Android 11+");
            checkAndInstall();
        } else {
            //就算是Android11以前的，也至少需要读SD卡的权限，所以需要做权限判断
            if(PermissionUtil.checkPermission(this,PERMISSIONS,PERMISSION_REUQEST_CODE))
            {
                installApk();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==PERMISSION_REUQEST_CODE&&PermissionUtil.checkGrant(grantResults))
        {
            installApk();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.R)
    private void checkAndInstall() {
        //检查是否有MANAGE_EXTERNAL_STORAGE权限，没有则跳转到设置界面
        if(!Environment.isExternalStorageManager())
        {
            Intent intent=new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(Uri.fromParts("package",getPackageName(),null));
            startActivity(intent);
        }
        else {
            installApk();
        }
    }

    private void installApk() {
        String apkPath= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()+"/App2-debug.apk";
        Log.d("tang", "apkPath"+apkPath);
        //获取应用包管理器
        PackageManager pm = getPackageManager();
        //获取apk文件的包信息,用于判断应用是否损坏，如果损坏则pi为null
        PackageInfo pi = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if(pi==null)
        {
            Toast.makeText(this, "安装文件已损坏", Toast.LENGTH_SHORT).show();
            return;
        }
        Uri uri= Uri.parse(apkPath);
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N)
        {
            //通过FileProvider获取文件的URI访问方式
            uri= FileProvider.getUriForFile(this,getString(R.string.file_provider),new File(apkPath));
            Log.d("tang", String.format("new uri:%s",uri.toString()));
        }
        Intent intent=new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        //设置Uri的数据累次你为Apk文件
        intent.setDataAndType(uri,"application/vnd.android.package-archive");
        startActivity(intent);
    }
}
